package com.fizzgate.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class FIFOService {
    private final Logger logger = LoggerFactory.getLogger(FIFOService.class);
    private final LinkedBlockingDeque<Task> TASK_QUEUE = new LinkedBlockingDeque<>();
    private final ScheduledExecutorService ENGINE_POOL =
            Executors.newSingleThreadScheduledExecutor(new CustomizableThreadFactory("ENGINE-"));
    private  final AtomicInteger PID_BUILDER = new AtomicInteger(0);

    public void startTaskHandle() {
        ENGINE_POOL.scheduleAtFixedRate(
                () -> {
                    Task task = TASK_QUEUE.poll();
                    if (task == null) {
//                        logger.info("task queue is empty，no task to execute");
                    } else {
                        task.run();
                    }
                },
                0,
                1,
                TimeUnit.SECONDS);
    }
    public  void addTask(Runnable runnable) {
        Integer tId = PID_BUILDER.incrementAndGet();
        Task task = Task.builder().tId(tId).work(runnable).build();
        logger.info("submit task id [{}] to the queue", tId);
        TASK_QUEUE.add(task);
    }
}
